/**
 * @作者 zxy
 * @时间 2023-04-30 15:46
 * @说明 79. 单词搜索
 * 给定一个 m x n 二维字符网格 board 和一个字符串单词 word 。如果 word 存在于网格中，返回 true ；否则，返回 false 。
 * 单词必须按照字母顺序，通过相邻的单元格内的字母构成，其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母不允许被重复使用。
 * 示例 1：
 * 输入：board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCED"
 * 输出：true
 */
public class Solution {
    String word;

    /**
     * 执行用时：1607 ms, 在所有 Java 提交中击败了5.00%的用户
     * 内存消耗：42.9 MB, 在所有 Java 提交中击败了5.12%的用户
     * @param board
     * @param word
     * @return
     */
    public boolean exist(char[][] board, String word) {
        this.word = word;
        for (int i = 0; i < board.length; i++) {
            for (int i1 = 0; i1 < board[i].length; i1++) {
                if (board[i][i1] == word.charAt(0)) {
                    if (search(copy(board), 1, i, i1)) return true;
                }
            }
        }
        return false;
    }

    private boolean search(char[][] board, int wordIndex, int i, int j) {
        if (wordIndex > this.word.length() - 1) return true;
        if (i > 0 && board[i - 1][j] == word.charAt(wordIndex)) {
            char[][] clone = copy(board);
            clone[i][j] = 0;
            if (search(clone, wordIndex + 1, i - 1, j)) return true;
        }
        if (i < board.length - 1 && board[i + 1][j] == word.charAt(wordIndex)) {
            char[][] clone = copy(board);
            clone[i][j] = 0;
            if (search(clone, wordIndex + 1, i + 1, j)) return true;
        }
        if (j > 0 && board[i][j - 1] == word.charAt(wordIndex)) {
            char[][] clone = copy(board);
            clone[i][j] = 0;
            if (search(clone, wordIndex + 1, i, j - 1)) return true;
        }
        if (j < board[i].length - 1 && board[i][j + 1] == word.charAt(wordIndex)) {
            char[][] clone = copy(board);
            clone[i][j] = 0;
            if (search(clone, wordIndex + 1, i, j + 1)) return true;
        }
        return false;
    }

    private char[][] copy(char[][] chars) {
        char[][] chars1 = new char[chars.length][chars[0].length];
        for (int i = 0; i < chars.length; i++) {
            for (int i1 = 0; i1 < chars[i].length; i1++) {
                chars1[i][i1] = chars[i][i1];
            }
        }
        return chars1;
    }

    public static void main(String[] args) {
        new Solution().exist(new char[][]{
                {'C', 'A', 'A'}, {'A', 'A', 'A'}, {'B', 'C', 'D'}
        }, "AAB");
    }
}
